const fs = require("fs");
const path = require("path");
const Router = require("koa-router");
const User = require("../data/schema/login");
const jwt = require("jsonwebtoken");
const send = require("koa-send");
const {
  bcryptPassword,
  confirmPassword,
  secret,
  startZIP,
  showErr,
  vertifyToken,
  findPageIndex,
  toCapital,
  gainPageName,
  getWidgetNames,
  filterProps,
  getImgaes,
} = require("../utils/index");
const uuid = require("uuid");
const router = new Router();
const shell = require("shelljs");

/*配置router路由*/
router.get("/login", async (ctx) => {
  const { userName, password } = ctx.query;
  /*查找用户*/
  await User.find({ username: userName }, (err, result) => {
    showErr(err);

    if (result.length > 0) {
      /*验证密码*/
      const flag = confirmPassword(password, result[0].password);

      const userId = result[0].id;
      const info = {
        username: userName,
        password,
      };
      const token = jwt.sign(info, secret);

      /*如果验证密码通过*/
      if (flag) {
        ctx.body = {
          status: 200,
          message: "登录成功！",
          data: {
            userId,
            token,
            userName,
          },
        };
      } else {
        ctx.body = {
          status: 201,
          message: "密码错误！",
        };
      }
    } else {
      ctx.body = {
        status: 404,
        message: "没有该用户！",
      };
    }
  });
});
/*注册路由*/
router.post("/register", async (ctx) => {
  const { userName, password } = ctx.request.body;

  const result = await User.find({ username: userName }, async (err) => {
    showErr(err);
  });

  /*如果数据库里面已经有了这个用户*/
  if (result.length > 0) {
    ctx.body = {
      status: 201,
      message: "用户已存在！",
    };
  } else {
    /*将密码转换成hash*/
    const hash = bcryptPassword(password);
    const newUser = new User({
      username: userName,
      password: hash,
    });

    await new Promise((resolve, reject) => {
      newUser.save((err) => {
        if (err) return reject(err);

        ctx.body = {
          status: 200,
          message: "注册成功！",
        };
        resolve();
      });
    });
  }
});

router.get("/getpages", async (ctx) => {
  const { token } = ctx.query;
  const info = await vertifyToken(token, ctx);
  const { username } = info;
  const user = await User.find({ username });
  if (user.length > 0) {
    const pages = user[0].pages;
    ctx.body = {
      status: 200,
      data: { pages },
      message: "获取页面数据成功！",
    };
  } else {
    ctx.body = {
      status: 404,
      message: "找不到用户！",
    };
  }
});

router.post("/addpage", async (ctx) => {
  const { pageInfo, token } = ctx.request.body;

  const info = await vertifyToken(token, ctx);
  const { username } = info;

  const findUser = async () => {
    const user = await User.find({ username });
    if (user.length > 0) return user;
    return null;
  };

  const user = await findUser();

  if (user.length > 0) {
    const addPage = (pageInfo) => {
      const newPages = user[0].pages;
      const id = uuid.v1();
      newPages.push({ ...pageInfo, id });
      return newPages;
    };

    const newPages = addPage(pageInfo);

    const updatePages = async () => {
      await User.updateOne(
        { username: username },
        { pages: newPages },
        (err) => {
          showErr(err);
        }
      );
    };
    await updatePages();

    ctx.body = {
      status: 200,
      message: "添加页面成功！",
    };
  } else {
    ctx.body = {
      status: 404,
      message: "没有用户信息！",
    };
  }
});

router.post("/delpage", async (ctx) => {
  const { token, pageId } = ctx.request.body;
  const info = await vertifyToken(token, ctx);

  const { username } = info;

  const user = await User.find({ username });

  const getNewPages = () => {
    const oldPages = user[0].pages;
    const newPages = user[0].pages;
    const index = findPageIndex(oldPages, pageId);
    newPages.splice(index, 1);
    return newPages;
  };

  const newPages = getNewPages();

  await User.updateOne({ username: username }, { pages: newPages }, (err) => {
    if (err) {
      ctx.body = {
        status: 500,
        message: "删除失败！",
      };
    }
  });

  ctx.body = {
    status: 200,
    message: "删除成功！",
  };
});

router.post("/save", async (ctx) => {
  const { token, componentData, pageId } = ctx.request.body;
  const info = await vertifyToken(token, ctx);

  const { username } = info;
  const user = await User.find({ username });

  const update = async () => {
    const oldPages = user[0].pages;
    const newPages = [...oldPages];
    const index = findPageIndex(oldPages, pageId);
    newPages[index].componentData = componentData;

    return new Promise((resolve, reject) => {
      User.updateOne({ username: username }, { pages: newPages }, (err) => {
        if (err) {
          ctx.body = {
            status: 500,
            message: "保存失败！",
          };
          reject(err);
        } else {
          ctx.body = {
            status: 200,
            message: "保存成功！",
          };
          resolve();
        }
      });
    });
  };

  if (user.length > 0) {
    await update();
  }
});

router.get("/getdata", async (ctx) => {
  const { pageId, token } = ctx.query;
  const info = await vertifyToken(token, ctx);
  const { username } = info;
  const user = await User.find({ username: username });

  if (user.length > 0) {
    const pages = user[0].pages;
    const index = findPageIndex(pages, pageId);
    const componentData = pages[index].componentData;

    ctx.body = {
      status: 200,
      data: componentData,
      message: "查询成功！",
    };
  }
});

router.post("/publish", async (ctx) => {
  const { token } = ctx.request.body;
  const { username } = await vertifyToken(token);
  const user = await User.find({ username: username });

  if (user.length > 0) {
    const pages = user[0].pages;
    const data = JSON.stringify(pages);

    const pagesPath = path.resolve(__dirname, "../template/demo/src/json.js");
    const id = uuid.v1();

    /*先把pages的数据写入*/
    fs.writeFileSync(
      pagesPath,
      `
      const id = '${id}' 
      const pages = 
    ${data}

    export default pages;
     `,
      "utf8"
    );

    pages.forEach((_, index) => {
      const pagePath = path.resolve(
        __dirname,
        `../template/demo/src/pages/page${index + 1}.js`
      );
      fs.writeFileSync(
        pagePath,
        `
        import BaseComponent from '../components/common/BaseComponent'
        import Wrap from '../components/common/Wrap'
        import pages from "../json";
        const pageData = pages[${index}];
        const Page = () => {
          const componentList = pageData.componentData      
          return (
            <div>
              {componentList.map((widget) => {
                return (
                  <Wrap key={widget.id} widget={widget}>
                    <BaseComponent widget={widget} />
                  </Wrap>
                );
              })}
            </div>
          );
        };
        export default Page;
        
       `,
        "utf8"
      );
    });

    /*然后再写router创建页面路由*/
    const routerPath = path.resolve(
      __dirname,
      "../template/demo/src/router/router.js"
    );
    fs.writeFileSync(
      routerPath,
      `import { HashRouter as Router, Route, Switch, Redirect } from "react-router-dom";
      ${pages
        .map((_, index) => {
          return `import Page${index + 1} from '../pages/page${index + 1}'\n `;
        })
        .join(" ")}
      const RouterView = () => {
        return (
          <Router>
          <Redirect to="${pages[0].pageUrl}"></Redirect>
            <Switch>
              ${pages
                .map((page, index) => {
                  return `<Route path='${page.pageUrl}' component={Page${
                    index + 1
                  }}></Route>\n `;
                })
                .join(" ")}
            </Switch>
          </Router>
        );
      };
      export default RouterView;
      
        `,
      "utf8"
    );

    try {
      const temPath = path.join(__dirname, "../template/script.js");
      shell.exec(`node ${temPath}`);
      ctx.body = {
        status: 200,
        message: "部署成功！",
      };
    } catch (err) {
      ctx.body = {
        status: 500,
        message: "部署失败！",
      };
      return console.log(err);
    }
  } else {
    ctx.body = {
      status: 404,
      message: "没有该用户！",
    };
  }
  // startZIP();
});

router.post("/generate", async (ctx) => {
  const { token } = ctx.request.body;
  const { username } = await vertifyToken(token);
  const user = await User.find({ username: username });

  if (user.length > 0) {
    const pages = user[0].pages;
    const data = JSON.stringify(pages);

    const pagesPath = path.resolve(__dirname, "../template/test/src/json.js");
    const id = uuid.v1();
    /*先把pages的数据写入*/
    fs.writeFileSync(
      pagesPath,
      `
      const id = '${id}' 
      const pages = 
    ${data}

    export default pages;
     `,
      "utf8"
    );

    /*然后再写router创建页面路由*/
    const routerPath = path.resolve(
      __dirname,
      "../template/test/src/router/router.js"
    );

    fs.writeFileSync(
      routerPath,
      `import { HashRouter as Router, Route, Switch, Redirect } from "react-router-dom";
      ${pages
        .map((page) => {
          return `
          import ${toCapital(page.pageUrl)} from '../pages/${toCapital(
            page.pageUrl
          )}'\n `;
        })
        .join("")}
      const RouterView = () => {
        return (
          <Router>
          <Redirect to="${pages[0].pageUrl}"></Redirect>
            <Switch>
              ${pages
                .map((page) => {
                  return `<Route path='${page.pageUrl}' component={${toCapital(
                    page.pageUrl
                  )}}></Route>\n `;
                })
                .join(" ")}
            </Switch>
          </Router>
        );
      };
      export default RouterView;
      
        `,
      "utf8"
    );

    pages.forEach((page) => {
      const pagePath = path.resolve(
        __dirname,
        `../template/test/src/pages/${toCapital(page.pageUrl)}.jsx`
      );
      const componentData = page.componentData;

      fs.writeFileSync(
        pagePath,
        `
        ${getWidgetNames(componentData)
          .map((name) => {
            return `import ${toCapital(
              "/" + name
            )} from '../components/widget/${toCapital("/" + name)}.jsx' \n`;
          })
          .join("")}

          ${getImgaes(componentData).map((name) => {
            const imgName = name.replace(/[0-9]/g, "a").replace(/-/g, "b");
            return `import ${imgName} from '../assets/imgs/${name}.js' \n`;
          })}

        const ${toCapital(page.pageUrl)} = () => {
          return (
            <div>
              ${componentData
                .map((widget) => {
                  return `${filterProps(widget)}\n`;
                })
                .join("")}
            </div>
          );
        };

        export default ${toCapital(page.pageUrl)};
       `,
        "utf8"
      );
    });

    ctx.body = {
      status: 200,
      message: "代码生成成功！",
    };
  } else {
    ctx.body = {
      status: 404,
      message: "没有该用户！",
    };
  }
});

router.get("/download", async (ctx) => {
  const distPath = path.join(__dirname, '../template/')
  await startZIP()
  ctx.attachment()
  await send(ctx, 'dist.zip', { root: distPath });
});

router.get("/", async (ctx) => {
  await ctx.render("index", {
    title: "ejs",
  });
});

module.exports = router;
